const ora = require('ora')
const shell = require('shelljs')

function exec(script = '') {
  return new Promise((resolve, reject) =>
    shell
      .exec(script, { async: true })
      .on('close', code => (code === 0 ? resolve() : reject(code)))
  )
}

;(async function () {
  const spinner = ora()
  try {
    const version = process.argv[2]
    if (typeof version !== 'string' || !version.trim()) {
      throw new Error()
    }
    await exec('npm run lint')
    await exec(`npm --no-git-tag-version version ${version.trim()}`)
    await exec('git add .')
    await exec('git commit -m "chore(all): 更新npm版本号"')
    await exec('conventional-changelog -p angular -i CHANGELOG.md -s -r 0')
    await exec('npm run lint')
    await exec('git add .')
    await exec('git commit -m "docs(all): 更新changelog"')
    await exec(`git tag v${version.trim()}`)
    await exec('git push origin --tags')
    await exec('git push origin master')
    spinner.succeed('创建版本号成功！')
  } catch (error) {
    spinner.fail('创建版本号失败！')
  }
})()
